package eleven.senven.hpb.fragment;


import android.support.v4.app.Fragment;
import android.widget.Toast;

import com.alibaba.fastjson.JSONObject;
import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshListView;
import com.lidroid.xutils.BitmapUtils;
import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.http.client.HttpRequest;

import org.androidannotations.annotations.AfterViews;
import org.androidannotations.annotations.EFragment;
import org.androidannotations.annotations.ViewById;

import java.util.ArrayList;
import java.util.List;

import eleven.senven.hpb.R;
import eleven.senven.hpb.adapter.MagazineAdapter;
import eleven.senven.hpb.bean.MagazineBaseBean;
import eleven.senven.hpb.bean.MagazintResultBean;
import eleven.senven.hpb.config.UrlsHolder;

@EFragment(R.layout.fragment_classification)
public class ClassificationFragment extends Fragment implements PullToRefreshBase.OnRefreshListener2{
    @ViewById(R.id.magazine_list)
    PullToRefreshListView listView;
    private List<MagazintResultBean> datas;
    private MagazineAdapter adapter;
    private int page=1;

    @AfterViews
    void initView(){
        datas=new ArrayList<>();
        BitmapUtils bitmapUtils=new BitmapUtils(getActivity());
        adapter=new MagazineAdapter(datas,getActivity(),bitmapUtils);
        listView.setMode(PullToRefreshBase.Mode.PULL_FROM_END);
        listView.setAdapter(adapter);
        listView.setOnRefreshListener(this);
        loadData();
    }

    private void loadData() {
        new HttpUtils().send(HttpRequest.HttpMethod.GET, UrlsHolder.getInstance().getMagUrl(page), new RequestCallBack<String>() {
            @Override
            public void onSuccess(ResponseInfo<String> responseInfo) {
                String result=responseInfo.result;
                MagazineBaseBean baseBean= JSONObject.parseObject(result,MagazineBaseBean.class);
                List<MagazintResultBean> list = baseBean.getResult();
                datas.addAll(list);
                adapter.notifyDataSetChanged();
            }

            @Override
            public void onFailure(HttpException e, String s) {
                Toast.makeText(getActivity(),"失败了",Toast.LENGTH_SHORT).show();
            }
        });
    }

    @Override
    public void onPullDownToRefresh(PullToRefreshBase refreshView) {
       // Toast.makeText(getActivity(),"下拉",Toast.LENGTH_SHORT).show();
        page++;
        loadData();

    }

    @Override
    public void onPullUpToRefresh(PullToRefreshBase refreshView) {
       // Toast.makeText(getActivity(),"上拉",Toast.LENGTH_SHORT).show();
        page++;
        loadData();

    }
}
